package com.dp.quickStart;

import lombok.experimental.Accessors;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: dupeng
 * @CreateTime: 2024-12-23  11:27
 * @Description: TODO
 */
@Accessors
public class Demo2 {

    private RestHighLevelClient client;

    @BeforeEach
    public void before() {
        client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://152.136.59.90:9200")
        ));
    }

    @Test
    public void test() throws IOException {
        //创建查询对象
        SearchRequest searchRequest = new SearchRequest("items");

        //构建查询逻辑
//        searchRequest.source(new SearchSourceBuilder()
//                .query(QueryBuilders
//                        .boolQuery().must(QueryBuilders.matchQuery("name","手机"))
//                        .filter(QueryBuilders.termQuery("brand", "小米"))
//                        .filter(QueryBuilders.rangeQuery("price").gte(30000).lte(50000)))
//                .size(3)
//                .sort(new FieldSortBuilder("price").order(SortOrder.DESC))
//                .highlighter(SearchSourceBuilder.highlight().field("name"))

        searchRequest.source()
                .query(QueryBuilders.boolQuery()
                        .must(QueryBuilders.matchQuery("name","手机"))
                        .filter(QueryBuilders.termQuery("brand", "小米"))
                        .filter(QueryBuilders.rangeQuery("price").gte(30000).lte(50000)))
                .sort(new FieldSortBuilder("price").order(SortOrder.DESC))
                .highlighter(SearchSourceBuilder.highlight().field("name"))
                .size(3);

        //执行查询
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        //解析响应
        parseResponse(response);
    }

    private void parseResponse(SearchResponse response) {
        System.out.println("以下是响应");
        System.out.println(response);
    }


    @AfterEach
    public void after() throws Exception {
        client.close();
    }

}
